<script setup lang="tsx">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import {
  PlusSearch,
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import { addDialog } from "@/components/ReDialog";
import dialogForms, { type FormProps } from "./handle.vue";
import { getShipList, toSendShip } from "@/api/finance";
import { utils, writeFile } from "xlsx";
import {
  formatDate,
  underscoreToCamel,
  fixImageUrl,
  handleImagesUpload
} from "@/utils/common";
import { getKeyVal } from "@/api/common";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";
defineOptions({
  name: "FinanceShip"
});
import { useMenu } from "@/utils/power";
const power = useMenu(["exportExcel", "ship"]);

const types = ref([
  { label: "云盒", value: 1 },
  // { label: "算力", value: 2 },
  { label: "水机", value: 3 },
  { label: "充电宝", value: 4 }
]);

const getTypesOptions = async () => {
  try {
    const res = await getKeyVal("GoodsType");
    const results = res.data.map(item => ({
      label: item.title,
      value: item.type
    }));
    types.value.push(...results);
  } catch (error) {}
};
getTypesOptions();

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "选择时间范围",
    labelWidth: 120,
    width: 600,
    prop: "dateRange",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "daterange",
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "产品类型",
    prop: "type",
    valueType: "select",
    options: computed(() => types.value)
  },
  {
    label: "状态",
    prop: "shipStatus",
    valueType: "select",
    options: [
      {
        label: "待发货",
        value: 0,
        color: "red"
      },
      {
        label: "已收货",
        value: 1,
        color: "blue"
      },
      {
        label: "待收货",
        value: 2,
        color: "green"
      }
    ]
  }
];
const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "keyWord") {
    return;
  }
  onKeywordChange(value);
};

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  params,
  loadData,
  onKeywordChange,
  onCurrentChange
} = useColumns();
const columnsRef = computed(() => {
  if (power.value.ship) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

const fullscreenLoading = ref(false);

const exportExcel = async () => {
  try {
    const postData = Object.assign({}, params.value);
    postData.pageSize = 5000;
    postData.page = 1;
    const resData = await getShipList(postData);
    const data = resData.data.items;
    data.map(item => {
      item.shipStatus =
        item.shipStatus === 0
          ? "待发货"
          : item.shipStatus === 1
            ? "已收货"
            : "待收货";
    });
    const dataKeys: string[] = [
      // "account",
      "name",
      "GoodsTitle",
      "lxfs",
      "address",
      "shipStatus",
      "shipTime",
      "shipCompany",
      "shipNo",
      "payShip",
      "orderTime"
    ];
    const titleList: string[] = [
      // "账号",
      "姓名",
      "商品名称",
      "联系方式",
      "地址",
      "发货状态",
      "发货时间",
      "快递公司",
      "快递单号",
      "快递费",
      "下单时间"
    ];
    const res: string[][] = data.map(item => {
      const arr = [];
      dataKeys.forEach(column => {
        arr.push(item[column]);
      });
      return arr;
    });
    res.unshift(titleList);
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `${formatDate(new Date())} 发货报表.xlsx`);
    ElMessage.success(`导出成功${data.length}条`);
  } catch (error) {
    console.log(error, "exportError");
  }
};

const shipFormColumns: PlusColumn[] = [
  // {
  //   label: "账号",
  //   width: 120,
  //   prop: "account",
  //   valueType: "input"
  // },
  {
    label: "收件人",
    width: 120,
    prop: "name",
    valueType: "input"
  },
  {
    label: "联系方式",
    width: 120,
    prop: "lxfs",
    valueType: "input"
  },
  {
    label: "收件地址",
    width: 120,
    prop: "address",
    valueType: "input"
  },
  {
    label: "物流状态",
    prop: "shipStatus",
    valueType: "select",
    options: [
      {
        label: "未发货",
        value: 0
      },
      {
        label: "已发货",
        value: 1
      },
      {
        label: "待收货",
        value: 2
      }
    ]
  },
  {
    label: "快递单号",
    width: 120,
    prop: "shipNo",
    valueType: "input"
  },
  {
    label: "快递公司",
    width: 120,
    prop: "shipCompany",
    valueType: "input"
  },
  // {
  //   label: "快递费",
  //   width: 120,
  //   prop: "payShip",
  //   valueType: "input"
  // },
  {
    label: "物流凭证",
    width: 120,
    prop: "shipImage",
    valueType: "img"
  }
];
const shipFormRef = ref();
const shipVisible = ref(false);
const shipConfirmLoading = ref(false);
const shipValues = ref({});
function sendShipClick(row) {
  const data = underscoreToCamel(row);
  shipValues.value = data || {};
  shipVisible.value = true;
}

const handleSubmitShip = async (value: FieldValues) => {
  const updatedValues = { ...shipValues.value };
  shipConfirmLoading.value = true;
  try {
    await toSendShip(updatedValues);
    shipVisible.value = false;
    shipConfirmLoading.value = false;
    shipFormRef.value?.formInstance?.resetFields();
  } catch (error) {
    shipConfirmLoading.value = false;
    console.log(error, "error");
  }
};
const imageFile = (path: any) => {
  return path.split(",").map((path: any) => {
    return { url: fixImageUrl(path), name: path.split("/").pop() };
  });
};

const productImageRef = ref();
const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  console.log("iconsucc", "color: MidnightBlue; font-size: 20px;", file, res);
  shipValues.value.shipImage = res.data;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  shipValues.value.shipImage = undefined;
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    files
  );
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>发货管理</h3>
        </template>
        <template v-if="power.exportExcel" #extra>
          <el-popconfirm
            title="是否确认导出(默认导出最大5000条数据)"
            @confirm="exportExcel"
          >
            <template #reference>
              <el-button
                v-loading.fullscreen.lock="fullscreenLoading"
                type="primary"
                size="default"
                class="mb-4!"
              >
                导出Excel
              </el-button>
            </template>
          </el-popconfirm>
        </template>
        <PlusSearch
          class="mt-5"
          :hasUnfold="false"
          :columns="searchColumns"
          @reset="handleReset"
          @change="handleChange"
          @search="handleSearch"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #shipStatus="{ row }">
        <el-tag v-if="row.shipStatus == 1" type="success">已收货</el-tag>
        <el-tag v-else-if="row.shipStatus == 2" type="danger">待收货</el-tag>
        <el-tag v-else type="primary">未发货</el-tag>
      </template>
      <template #voucherimage="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="row.voucherimage"
          :preview-src-list="dataList.map(v => v.voucherimage)"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
      <template v-if="power.ship" #operation="{ row }">
        <el-button
          v-if="row.shipStatus == 0 || row.shipStatus == null"
          type="primary"
          size="small"
          @click="sendShipClick(row)"
        >
          发货
        </el-button>
        <el-tag v-else type="success">已发货</el-tag>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="shipFormRef"
      v-model:visible="shipVisible"
      v-model="shipValues"
      draggable
      :form="{ columns: shipFormColumns, rules: shipRules, labelWidth: 120 }"
      :dialog="{ shipConfirmLoading }"
      title="发货处理详情"
      @confirm="handleSubmitShip"
    >
      <template #plus-field-shipImage>
        <el-upload
          ref="productImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            shipValues &&
            shipValues.shipImage &&
            shipValues.shipImage.length > 0
              ? imageFile(shipValues.shipImage)
              : []
          "
          :on-success="handleIconImageSuccess"
          :on-remove="handleIconImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleIconImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped></style>
